<template>
  <div :class="{'mobile-detail-wrap':showMobilePage}">
    <div v-loading="loading" class="sign-detail-container no-margin">
      <div v-if="!permissionDenied" class="sign-detail-content small-padding">
        <Title title="基础信息" style="font-size:16px; margin-bottom:7px"/>
        <baseInfo ref="userInfo" :base-info="noticeInfo"/>
        <Title title="询单内容" style="font-size:16px; margin:23px 0 7px">
          <span v-if="noticeInfo.isUpdated" class="update-badge">询单已更新</span>
        </Title>
        <orderDetail ref="userInfo" :order-detail="noticeInfo"/>
        <Title title="特殊备注/追加说明" style="font-size:16px; margin: 23px 0 16px" />
        <remarksTable :data="remarksData" />
        <Title title="通知人员" style="font-size:16px; margin:23px 0 10px" class="notice-title"/>
        <noticeTable ref="noticeTable" :show-notice-btn="showNoticeBtn" :is-creator="isCreator" :query-order-id="Number(id)" @updateInfo="updateInfo"/>
        <fixed-pagination>
          <div class="center">
            <el-button type="primary" size="small" class="global-plain-btn mr10" @click="toOrderList()" >查看关联订单</el-button>
            <!-- 1询单中 2已撤回 3已完成-->
            <el-button v-if="showNoticeBtn" type="primary" size="small" class="submit-btn" @click="toFinish()" >完成询单</el-button>
            <!-- <el-button v-if="(noticeInfo.status === 2 || noticeInfo.status === 3) && hasRouteAuth('crm:flyNotice:create')" type="primary" size="small" class="submit-btn" @click="toCreate()">复制</el-button> -->
            <el-dropdown v-if="(noticeInfo.status === 2 || noticeInfo.status === 3) && hasRouteAuth('crm:flyNotice:create')" trigger="click">
              <el-button type="primary" size="small" class="submit-btn mr10">复制<i class="el-icon-caret-top"/></el-button>
              <el-dropdown-menu slot="dropdown" style="padding: 0;">
                <el-dropdown-item v-for="item in againData" :key="item.id" style="text-align: center" class="tabel-btn" @click.native="toCreate(item.id)">{{ item.name }}</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-button v-if="noticeInfo.status === 2 && isCreator" type="primary" size="small" class="submit-btn" @click="toEdit()">编辑</el-button>
            <el-button v-if="showNoticeBtn" type="danger" size="small" plain @click="toRevoke()">撤回</el-button>
            <el-button class="back-btn cancel-btn-style" size="small" @click="toBack()">返回</el-button>
          </div>
        </fixed-pagination>
        <log ref="logs" :id="id" :is-update="isUpdate"/>
        <el-image :src="hoverSrc" class="hover-img"/>
      </div>
      <DeniedPlaceholder v-else style="margin-top: 0"/>
    </div>
  </div>
</template>
<script>
// 组件
import ListTab from '@/components/ListTab';
import log from '../components/flyLogs';
import baseInfo from '../components/baseInfo';
import orderDetail from '../components/orderDetail';
import noticeTable from '../components/noticeTable';
import Title from '@/components/Title';
import remarksTable from '../components/remarksTable';
// api methods
import { queryOrderInfo, editOrderStatus } from '@/api/flyNotice';
import { hasRouteAuth } from '@/utils/permission';
// img
import emptyIcon from '@/assets/home/emptyIcon.png';
import progress from '@/assets/auditProcess/progress.png';
import finish from '@/assets/auditProcess/process_status_4.png';
import revoke from '@/assets/auditProcess/process_status_7.png';
// mixins
import { showModal } from '@/utils/message';
import { mapState } from 'vuex';

export default {
  components: {
    ListTab,
    baseInfo,
    Title,
    orderDetail,
    log,
    noticeTable,
    remarksTable
  },
  data() {
    return {
      id: '',
      hasRouteAuth,
      progress,
      finish,
      revoke,
      emptyIcon,
      isUpdate: false,
      noticeInfo: {},
      activeTab: '',
      accountTabs: [], // 账户列表
      accountsInfoItem: {},
      loading: false,
      permissionDenied: false, // 详情页是否可查看
      cancelToken: null,
      remarksData: [],
      againData: [{ id: 0, name: '全部' },
        { id: 1, name: '仅感兴趣' },
        { id: 3, name: '仅待响应' },
        { id: 2, name: '待响应+感兴趣' }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    showAccountInfo() { // 展示账号信息
      return this.accountTabs.length > 0;
    },
    hoverSrc() {
      switch (this.noticeInfo.status) {
        case 1:return this.progress;
        case 2:return this.revoke;
        case 3:return this.finish;
      }
    },
    isCreator() {
      return this.noticeInfo.creatorId === this.userInfo.id;
    },
    showNoticeBtn() {
      return this.noticeInfo.status === 1 && this.isCreator;
    }
  },
  created() {
    this.id = Number(this.$route.query.id);
    this.getInfo();
  },
  methods: {
    // 获取详情
    getInfo() {
      if (isNaN(this.id) || !this.id) {
        this.$message.error('无法获取询单ID，请重试或联系管理员');
        return;
      }
      this.loading = true;
      queryOrderInfo(this.id).then(res => {
        this.loading = false;
        if (res.code !== 200) {
          this.$message.error(res.message);
          return;
        }
        this.noticeInfo = res.data;
        this.handleRemarksData(this.noticeInfo);
      }).catch(err => {
        if (err.code === 403) {
          this.permissionDenied = true;
        }
        this.loading = false;
        console.log(err);
      });
    },
    handleDateSort() {
      this.remarksData.forEach(it => {
        it.timestamp = new Date(it.updateDate).getTime();
      });
      function sortByTime(arr) {
        return arr.sort((a, b) => a.timestamp - b.timestamp);
      }
      this.remarksData = sortByTime(this.remarksData);
    },
    handleRemarksData(data) {
      const { remarks, queryOrderAdditionals } = data;
      if (remarks) {
        remarks.forEach(it => {
          it.isRemarks = true;
        });
      }
      this.remarksData = queryOrderAdditionals ? [...remarks, ...queryOrderAdditionals] : [...remarks];
      this.handleDateSort();
    },
    updateInfo() {
      this.getInfo();
      this.$refs['noticeTable'].updateInfo();
      this.isUpdate = !this.isUpdate;
    },
    // 再次发起（复制）
    toCreate(createType) {
      this.$router.push({
        name: 'flyNoticeCreate',
        query: {
          id: this.id,
          createNew: true,
          createType
        }
      });
    },
    // 编辑
    toEdit() {
      this.$router.push({
        name: 'flyNoticeEdit',
        query: {
          id: this.id
        }
      });
    },
    // 撤回
    toRevoke() {
      showModal('请确认是否撤回询单，撤回后用户将不可响应', '', {
        iconClass: 'del-icon'
      }).then(() => {
        const data = {
          id: this.id,
          status: 2
        };
        editOrderStatus(data).then(res => {
          this.updateInfo();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    // 完成
    toFinish() {
      showModal('确定完成该询单?', '', {
        iconClass: 'del-icon'
      }).then(() => {
        const data = {
          id: this.id,
          status: 3
        };
        editOrderStatus(data).then(res => {
          this.updateInfo();
        }).catch(err => { console.log(err); });
      }).catch(() => {
        return false;
      });
    },
    // 跳转渠道单列表
    toOrderList() {
      const { sn } = this.noticeInfo;
      if (!sn) {
        this.$message.warning('无法获取关联订单id');
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'allOrder',
        query: {
          queryOrderSn: sn
        }
      });
      window.open(routeUrl.href, '_blank');
    },
    toBack() {
      this.$router.push({
        name: 'flyNotice'
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.mobile-detail-wrap {
  .sign-detail-container {
    border-radius: 6px;
  }
  .mobile-margin {
    margin: 12px 12px 100px !important;
  }
  .notice-title {
    margin-bottom: 0 !important;
  }
  &::v-deep {
    .table-list-tabs-item {
      margin: 0 12px !important;
    }
    .table-list-tabs-item:first-child {
      margin-left: 0 !important;
    }
    .list-tab {
      padding-right: 0 !important;
    }
    .mobile-item-content {
      padding-top: 8px !important;
    }
    .filter {
      margin-bottom: 0px !important;
    }
    .flyNotice-list {
      margin-top: 8px !important;
    }
    .notice-btn-group {
      margin-bottom: 8px !important;
    }
  }
}
.update-badge {
  background-color: #FFF2EB;
  color: #FD8546;
  font-size: 12px;
  padding: 4px 6px;
  border-radius: 4px;
  margin-left: 12px;
}
.sign-detail-container{
		margin:	16px;
		background: #fff;
		min-height: calc(100vh - 64px);
		.sign-detail-content{
      position: relative;
			padding: 16px 24px 56px;
		}
    .empty-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-top: 30px;
      .text {
        font-size: 14px;
        font-weight: 400;
        text-align: left;
        color: #999999;
        line-height: 20px;
        margin-top: 10px;
      }
      .blue {
        color: #406ef4;
      }
      img {
        width: 120px;
      }
    }
    .hover-img{
      position: absolute;
      width: 80px;
      height: 80px;
      right: 56px;
      top: 33px;
    }
	}
</style>
